//
//
//  掌上宏力
//
//  Created by admin on 17/3/9.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "LoginController.h"
#import "MainTabbarController.h"
#import "Reachability.h"


@interface LoginController ()<UITextFieldDelegate>

@property (nonatomic,strong) User *user;
@property (nonatomic,assign) BOOL login;

@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@property (weak, nonatomic) IBOutlet UIButton *forgetPWD;

@property (nonatomic,strong) Reachability *reachability;

@end

@implementation LoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    _forgetPWD.hidden = YES;
    self.userName.delegate = self;
    self.password.delegate = self;
    
    
    _user = [User currentUser];
    self.userName.text = _user.loginName;
    
    if (NetWorker.sharedNetWorker.isLogin) {
        self.password.text = _user.password;
    }else{
        self.password.text = @"";
    }
}

- (IBAction)forgetPWDClicked:(id)sender {
    
}

- (IBAction)loginIn:(id)sender {
    [self checkReachability];
    
}

//登录
-(void)goLogin{
    [SVProgressHUD show];
    User *user = [[User alloc] init];
    user.username = self.userName.text;
    user.password = self.password.text;
    
    [NetWorker loginWithUSER:user success:^(id result) {
        NetWorker.sharedNetWorker.isLogin = YES;
        NSArray *array = [JsonHelper arrayWithJsonString:result[@"Entity"]];
        
        NSMutableDictionary *dic = array[0];
        [user setUserInfoWithDictionary:dic];
        user.loginName = self.userName.text;
        //获取patientId和MedicalCard诊疗卡号
        [self getPatientIdWithUserId:user.userId success:^(NSString *patientId, NSString *medicalCard) {
            user.patientId = patientId;
            user.MedicalCard = medicalCard;
            dispatch_async(dispatch_get_main_queue(), ^{
                [LoginInfoTool sharedLoginInfoTool].currentUser = user;
                [[NetWorker sharedNetWorker] setLoginTime];
                [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                MainTabbarController *viewC = [[MainTabbarController alloc] init];
                [self presentViewController:viewC animated:YES completion:^{
                    self.password.text = @"";
                }];
            });
        }];
    } failure:^(id result) {
        NetWorker.sharedNetWorker.isLogin = NO;
        [SVProgressHUD showInfoWithStatus:@"用户名或密码错误！"];
    }];
    
}

- (void)checkReachability
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    self.reachability = [Reachability reachabilityForInternetConnection];
    [self.reachability startNotifier];
    [self updateInterfaceWithReachability:self.reachability];
}

/*!
 * Called by Reachability whenever status changes.
 */
- (void) reachabilityChanged:(NSNotification *)note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    [self updateInterfaceWithReachability:curReach];
}

- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
    //没有联网
    if (reachability.currentReachabilityStatus == NotReachable) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"暂时没有网络，请稍后再试" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:nil];
        [self performSelector:@selector(dismissAlertView) withObject:nil afterDelay:1.5];
    }else{
        [self goLogin];
    }
}
-(void)dismissAlertView{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)getPatientIdWithUserId:(NSString *)userId success:(void(^)(NSString *patientId,NSString *medicalCard))handler{
    /*{db:"OracleString",SqlNo:"40",ygbh:"128551",Page:"1"}
     {"Status":1,"Message":"数据加载成功","NewID":null,
     "Entity":"[{\"MEDICAL_CARD\":\"90000477\",\"PATIENT_ID\":\"90000477\",\"HRM_NAME\":\"杨慧萍\",\"JOBCLASSNAME\":\"长期聘用\",\"YGBH\":128551,\"LZBZ\":0}]","TotalPages":0,"TotalRowsCount":0}
     */
    
    NSDictionary *info = @{@"db":@"OracleString",@"SqlNo":@"40",@"ygbh":userId,@"Page":@"1"};
    NSString *url = [NSString stringWithFormat:@"%@%@",HOSPITAL_URL,COMMON_URL];
    [NetWorker getCommonDatasWithURLStr:url body:info success:^(id result) {
        NSArray *array = [JsonHelper arrayWithJsonString:result[@"Entity"]];
        NSDictionary *dic = array[0];
        NSString * patientId = dic[@"PATIENT_ID"];
        NSString * MedicalCard = dic[@"MEDICAL_CARD"];
        handler(patientId,MedicalCard);
    } failure:^(id result) {
        handler(@"",@"");
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    if ([textField isEqual:self.userName]) {
        [self.password becomeFirstResponder];
    }
    return YES;
}

@end
